import React, { useEffect, useMemo, useRef, useState } from 'react'
import axios from 'axios'
import City from './components/city/City'
import Search from './components/search/Search'
import SearchList from './components/searchList/ListSearch'
// [
//   {
//     type:A,
//     children:[
//       {

//       }
//     ]
//   },
//   {
//     type:A,
//     children:[
//       {
        
//       }
//     ]
//   }
// ]

const format = (cities) => {
  const res = []
  cities.forEach(value => {
    const firstLetter = value.pinyin[0].toUpperCase()
    const itemType = res.find(item => item.type === firstLetter)
    if(itemType) {
      itemType.children.push(value)
    }else{
      res.push({
        type:firstLetter,
        children:[value]
      })
    }
  })
  res.sort((a,b) => {
    return a.type.charCodeAt() - b.type.charCodeAt()
  })
  // console.log(res)
  return res
}



const App = () => {
  const [city,setCity] = useState([])
  const [navList,setNavList] = useState([])
  const [showSearch,setShowSearch] = useState(false)
  const [searchText,setSearchText] = useState('')

  const getCity = async () => {
    const res = await axios.get('https://m.maizuo.com/gateway',{
      headers:{
        "x-client-info":'{"a":"3000","ch":"1002","v":"5.2.1","e":"173088338914639202754887681","bc":"513200"}',
        "x-host":"mall.film-ticket.city.list"
      }
    })
    // console.log(res.data.data.cities)
    setCity(res.data.data.cities)
    setNavList(format(res.data.data.cities))
  }

  useEffect(() => {
    getCity()
  },[])

  const onChange = (value) => {
    // console.log('数据',value)
    setSearchText(value)
    setShowSearch(true)
  }

  const resultList = useMemo(() => {
    return city.filter(v => v.pinyin.includes(searchText) || v.name.includes(searchText))
  },[city,searchText])

  const onCancel = () => {
    setShowSearch(false)
  }

  return (
    <div className='box'>
      <Search onChange = {onChange}
        onCancel={onCancel}
      />
      <div className="content">
        {showSearch?
          <SearchList list={resultList}/>
        :
          <City list={navList}/>
        }
      </div>
      
      
    </div>
  )
}

export default App

